package com.shwread.android.qysw.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.shwread.android.qysw.bean.MessageEvent;
import com.shwread.android.qysw.visitMap.AMapUtil;
import com.shwread.android.qysw.visitMap.ClearEditText;
import com.shwread.android.qysw.visitMap.ToastUtil;
import com.shwread.android.qysw10000243.R;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import logic.lbs.PoiOverlay;

/**
 * 搜索因公外出拜访客户地址页面
 */

public class SearchLocationsActivity extends AppCompatActivity implements TextWatcher,
        PoiSearch.OnPoiSearchListener {
    private ListView searchResultLv;
    private ClearEditText eTKeyWord;
    private ProgressDialog progDialog = null;
    private List<PoiItem> poiItems;
    private PoiResult poiResult;
    private PoiSearch.Query query;
    private AMap aMap;
    private MapView mMapView = null;
    private String keyWord = "";
    private PoiSearch poiSearch;
    private String city = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_search_result);
        searchResultLv = (ListView) findViewById(R.id.searchResultLv);
        eTKeyWord = (ClearEditText) findViewById(R.id.keyWord);
        eTKeyWord.addTextChangedListener(this);

        city = getIntent().getStringExtra("city");
        mMapView = (MapView) findViewById(R.id.map);
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        searchResultLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                intent.putExtra("result", poiItems.get(position));
                intent.putExtra("lat", getIntent().getDoubleExtra("lat", 0));
                intent.putExtra("lon", getIntent().getDoubleExtra("lon", 0));
                setResult(1001, intent);
                String resultName=poiItems.get(position).getTitle();
                String address=poiItems.get(position).getCityName()+poiItems.get(position).getSnippet();
                Log.e("positionlan",poiItems.get(position).getLatLonPoint()+"");
                String latLonPoint=poiItems.get(position).getLatLonPoint()+"";
                String pointAry[]=latLonPoint.split(",");
                String lat=pointAry[0];
                String lon=pointAry[1];
                Log.e("latAry",lat);
                Log.e("lonAry",lon);

                //EventBus发送数据
//                EventBus.getDefault().post(new MessageEvent(address,lat,lon));
                EventBus.getDefault().post(new MessageEvent(resultName,lat,lon));
                SearchLocationsActivity.this.finish();
            }
        });
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String newText = s.toString().trim();
        if (!AMapUtil.IsEmptyOrNullString(newText)) {
            doSearchQuery();
        }
    }


    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        dissmissProgressDialog();// 隐藏对话框
//        hideSoftInput(SearchLocationsActivity.this, eTKeyWord);
        if (rCode == 1000) {
            if (result != null && result.getQuery() != null) {// 搜索poi的结果
                if (result.getQuery().equals(query)) {// 是否是同一条
                    poiResult = result;
                    // 取得搜索到的poiitems有多少页
                    poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    ResultAdapter adapter = new ResultAdapter(poiItems);
                    searchResultLv.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                    ArrayList<Marker> markers = new ArrayList();
                    List<SuggestionCity> suggestionCities = poiResult
                            .getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息

                    if (poiItems != null && poiItems.size() > 0) {
                        aMap.clear();// 清理之前的图标
                        PoiOverlay poiOverlay = new PoiOverlay(aMap, poiItems);
                        poiOverlay.removeFromMap();
                        for (int var1 = 0; var1 < poiItems.size(); ++var1) {
                            MarkerOptions options = (new MarkerOptions()).position(new LatLng((
                                    poiItems.get(var1)).getLatLonPoint().getLatitude(), (poiItems
                                    .get(var1)).getLatLonPoint().getLongitude())).title((poiItems
                                    .get(var1)).getTitle()).snippet((poiItems.get(var1))
                                    .getSnippet()).icon(BitmapDescriptorFactory.fromResource(R.drawable.mark));
                            Marker var2 = aMap.addMarker(options);
                            var2.setObject(Integer.valueOf(var1));
                            markers.add(var2);
                        }
                        poiOverlay.zoomToSpan();
                    } else if (suggestionCities != null
                            && suggestionCities.size() > 0) {
                        showSuggestCity(suggestionCities);

                    } else {
                        ToastUtil.show(SearchLocationsActivity.this,
                                "没有数据");
                    }
                }
            } else {
                ToastUtil.show(SearchLocationsActivity.this,
                        "没有数据");
            }
        } else {
            ToastUtil.showerror(SearchLocationsActivity.this, rCode);
        }
    }


    private void showSuggestCity(List<SuggestionCity> cities) {
        String infomation = "推荐城市\n";
        for (int i = 0; i < cities.size(); i++) {
            infomation += "城市名称:" + cities.get(i).getCityName() + "城市区号:"
                    + cities.get(i).getCityCode() + "城市编码:"
                    + cities.get(i).getAdCode() + "\n";
        }
        ToastUtil.show(SearchLocationsActivity.this, infomation);

    }

    private void dissmissProgressDialog() {
        if (progDialog != null) {
            progDialog.dismiss();
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    protected void doSearchQuery() {
        showProgressDialog();// 显示进度框
        query = new PoiSearch.Query(eTKeyWord.getText().toString(), "", city);//
        // 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(0);// 设置查第一页
        query.setCityLimit(true);

        poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();
    }

    private void showProgressDialog() {
        if (progDialog == null)
            progDialog = new ProgressDialog(this);
        progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progDialog.setIndeterminate(false);
        progDialog.setCancelable(false);
        progDialog.setMessage("正在搜索:\n" + keyWord);
        progDialog.show();
    }

    public class ResultAdapter extends BaseAdapter {
        private List<PoiItem> list;

        public ResultAdapter(List<PoiItem> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(SearchLocationsActivity.this).inflate(R.layout.item_search_result,
                        null);
                holder.tvResultName = (TextView) convertView.findViewById(R.id.tvResultName);
                holder.tvResultDis = (TextView) convertView.findViewById(R.id.tvResultDis);
                holder.tvAddr = (TextView) convertView.findViewById(R.id.tvAddr);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.tvResultName.setText(list.get(position).getTitle());
            holder.tvAddr.setText(list.get(position).getCityName() + list.get(position).getSnippet());


            holder.tvResultDis.setText(getDistance(list.get(position).getLatLonPoint().getLatitude() + "",
                    list.get(position).getLatLonPoint().getLongitude() + "", getIntent().getDoubleExtra
                            ("lat", 0) + "", getIntent().getDoubleExtra("lon", 0) + "")+"公里");
            return convertView;
        }

        class ViewHolder {
            TextView tvResultName, tvResultDis, tvAddr;
        }
    }

    public static void hideSoftInput(Context context, EditText edit) {
        edit.clearFocus();
        InputMethodManager inputmanger = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputmanger.hideSoftInputFromWindow(edit.getWindowToken(), 0);
    }

    public static String getDistance(String lat1Str, String lng1Str, String lat2Str, String lng2Str) {
        Double lat1 = Double.parseDouble(lat1Str);
        Double lng1 = Double.parseDouble(lng1Str);
        Double lat2 = Double.parseDouble(lat2Str);
        Double lng2 = Double.parseDouble(lng2Str);

        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double difference = radLat1 - radLat2;
        double mdifference = rad(lng1) - rad(lng2);
        double distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(difference / 2), 2) + Math.cos(radLat1)
                * Math.cos(radLat2) * Math.pow(Math.sin(mdifference / 2), 2)));
        distance = distance * EARTH_RADIUS;
        distance = Math.round(distance * 10000) / 10000;
        String distanceStr = distance + "";
        distanceStr = distanceStr.substring(0, distanceStr.indexOf("."));

        return distanceStr;//单位KM
    }

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    private static double EARTH_RADIUS = 6378.137;


}
